<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 品牌管理
 */
class BrandController extends Controller
{
    /* 品牌列表 */
    public function brand_list()
    {
        return view('brand/brand_list');
    }
    /* 品牌列表数据接口 */
    public function list_data()
    {
        $limit = request('limit', 10);

        $data = Brand::pageData($limit); //模型层方法
        // print_r($data);die;
        $json['code'] = 0;
        $json['msg'] = '成功';
        $json['count'] = DB::table('brand')->count();
        $json['data'] = $data['data'];
        exit(json_encode($json));
    }
    /* 上传文件 */
    public function upload(Request $request)
    {
        $file = $request->file('file'); //接收图片信息
        $path = $request->file->store('images'); //将图片放到public/images文件中
        return response()->json(['code' => 0, 'msg' => '图片  上传成功', 'data' => $path]);
    }
    /* 品牌添加 */
    public function brand_add(Request $request)
    {
        $data = $request->all();
        unset($data['_token']);
        unset($data['file']);
        $res = Brand::brandAdd($data);
        if ($res) {
            return response()->json(['code' => 0, 'msg' => '品牌添加成功']);
        } else {
            return response()->json(['code' => 1, 'msg' => '品牌添加失败']);
        }
    }
    /* 品牌删除 */
    public function brand_del()
    {
        $brand_id = request('brand_id');
        if (isset($brand_id)) {
            $res = Brand::brandDel($brand_id); //模型方法
            if ($res) {
                return response()->json(['code' => 1001, 'msg' => '删除成功']);die;
            } else {
                return response()->json(['code' => 1002, 'msg' => '删除失败']);die;
            }
        }
    }
    /* 渲染品牌修改页 */
    public function brand_save()
    {
        $brand_id = request('brand_id');
        $data = Brand::brandFirst($brand_id);
        return view('brand/brand_save', ['data' => $data]);
    }
    /* 执行品牌修改 */
    public function brand_saves(Request $request)
    {
        $brand_id = request('brand_id');

        $data = Brand::brandFirst($brand_id);
        $datas['brand_name'] = request('brand_name', $data['brand_name']);
        $datas['brand_logo'] = request('brand_logo', $data['brand_logo']);
        $datas['brand_url'] = request('brand_url', $data['brand_url']);
        $datas['brand_desc'] = request('brand_desc', $data['brand_desc']);
        $datas['brand_sort'] = request('brand_sort', $data['brand_sort']);
        // print_r($datas);die;
        $res = Brand::brandSave($data['brand_id'], $datas);
        if ($res) {
            return response()->json(['code' => 0, 'msg' => '品牌修改成功']);
        } else {
            return response()->json(['code' => 1, 'msg' => '品牌修改失败']);
        }
    }

}
